package com.yuan.blog.service;

import com.yuan.blog.constatns.RedisKey;
import com.yuan.blog.entity.InvitataionEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class InvitataionScoreService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IInvitataionService iInvitataionService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private ICommentService commentService;

    public void addIdToRedis(Integer id) {
        stringRedisTemplate.opsForSet().add(RedisKey.INVITATAION_SCORE, id.toString());
    }

    public Long getInvitationSize() {
        return stringRedisTemplate.opsForSet().size(RedisKey.INVITATAION_SCORE);
    }

    public void refreshScore() {

        // 1、帖子的数量的大于0，说明还有分数需要计算
        while (getInvitationSize() > 0) {

            // 2、弹出一个帖子id出来计算，弹出来redis中没有了
            Integer id = Integer.parseInt(stringRedisTemplate.opsForSet().pop(RedisKey.INVITATAION_SCORE));

            // 3、查询帖子的信息(是否制定)
            InvitataionEntity invitataionEntity = iInvitataionService.getById(id);
            Integer type = invitataionEntity.getType();

            // 4.查询帖子的点赞数量
            Long likeCount = likeService.getInvitataionLikeCount(1, id);

            // 5.查询帖子的评论数量
            Long commentCount = commentService.getInvitationCommentSize(id);

            // 6.开始计算分数
            int w = type == 2 ? 100 : 0; // 帖子如果制定了，加100
//            int a = 账号的权重
            Long x = likeCount * 20;
            Long y = commentCount * 40; // 评论的比重占比高一点
            // 把账号的权重也放进去

            double score = Math.log(Math.max(w + x + y, 1));

            // 7.更新分数
            invitataionEntity.setScore(score);
            iInvitataionService.updateById(invitataionEntity);

            log.debug("更新帖子【{}】，分数【{}】",id,score);

        }
    }
}
